import * as React from "react";

interface Actions {
  type: string;
  payload?: number;
}

interface InitialCount {
  count: number;
}

function init(initialCount: number) {
  return { count: initialCount };
}

function reducer(state: any, action: Actions) {
  switch (action.type) {
    case "inc":
      return { count: state.count + 1 };
    case "dec":
      return { count: state.count - 1 };
    case "reset":
      return init(action.payload!);
    default:
      throw new Error();
  }
}

export default function Reducer(initial: InitialCount) {
  const [state, dispatch] = React.useReducer(reducer, initial.count, init);

  return (
    <div>
      <div style={{ fontSize: "30px" }}>Count:{state.count}</div>
      <button onClick={() => dispatch({ type: "dec" })}>-</button>
      <button onClick={() => dispatch({ type: "inc" })}>+</button>
      <button
        onClick={() => dispatch({ type: "reset", payload: initial.count })}
      >
        清空
      </button>
    </div>
  );
}
